<?php


namespace app\common\lib\zlcr2;


use app\common\cachemodel\Orders;
use app\common\cachemodel\zlcr2\Zlcr2AstrTasks;
use app\common\cachemodel\zlcr2\Zlcr2UserAddQuestion;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestionComment;
use app\common\cachemodel\ZlcrAppeal;
use app\common\cachemodel\ZlcrAstr;
use app\common\cachemodel\ZlcrAstrAccount;
use app\common\cachemodel\ZlcrAstrMessage;
use app\common\lib\Push;
use app\common\lib\Util;
use app\common\model\MessageCenter;
use app\common\model\User;
use think\Log;
use think\queue\Job;

class QuestionAnswerJob
{
    /**
     * 问答接单检测 如果未接单则退款
     * @param Job $job
     * @param $jobData
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \app\common\lib\exception\ApiException
     * @throws \think\exception\PDOException
     */
    public function AstrReceivingCheck(Job $job, $jobData)
    {
        // $jobData = [
        //     'qid' =>咨询问题ID
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }
        try
        {
            $nowTime = time();
            $questionModel = new Zlcr2UserQuestion();
            $questionInfo = $questionModel->getInfoById($jobData['qid'], ['status', 'astr_id', 'order_num', 'uid']);
            if ($questionInfo['status'] === 2 || ($questionInfo['status'] === 4 && $questionInfo['astr_id'] === 0))
            {   // 问题 无人接单    或者  问题被弃答过 且此时 无人接单
                $OrderModel = new \app\common\cachemodel\Orders();
                $orders = $OrderModel->getInfoById($questionInfo['order_num']);
                $res = $OrderModel->refund($questionInfo['uid'], $orders, $orders['total_amount']);
                if ($res['status'])
                {
                    $questionModel->UpdateData($jobData['qid'], [
                        'status' => 11,
                        'success_time' => $nowTime,
                    ]);
                    // 发消息
                    if ($questionInfo['status'] === 2)
                    {   // 未被 占星师 抢单 过
                        $msgContent = "你开启的悬赏问答，订单编号：{$questionInfo['order_num']}因暂无咨询师接单自动取消，资金将原路返还，请注意查收。你可以重新下单。";
                        $smsTpid = 52337;
                        $tpContent = ['others' => $questionInfo['order_num']];
                    } else
                    {   // 被 占星师 抢单 过
                        $msgContent = "你开启的悬赏问答，订单编号：{$questionInfo['order_num']}因问题无法回答自动取消，资金将原路返还，请注意查收。请检查问题重新下单。 ";
                        $smsTpid = 52340;
                        $tpContent = ['order_num' => $questionInfo['order_num']];
                    }

                    // 消息中心添加信息
                    $messageData = [
                        'status' => 0,
                        'is_read' => 0,
                        'range' => $questionInfo['uid'],
                        'type' => 2,
                        'reid' => 0,
                        'cid' => 4,//
                        'title' => '订单取消通知',
                        'content' => $msgContent,// 消息中心跳转地址
                        'link' => "order_details?order_id={$questionInfo['order_num']}&order_type=22&need_auth=0",  // 订单详情
                        'target' => 'local',
                        'create_time' => $nowTime
                    ];
                    (new MessageCenter())->pushMessage($questionInfo['uid'], $messageData);
                    $pushData = ['action' => 'extend', 'target' => 'local', 'link' => "order_details?order_id={$questionInfo['order_num']}&order_type=22&need_auth=0"];
                    // PUSH推送报告首页
                    (new Push())->pushUserMsg($questionInfo['uid'], $msgContent, $pushData);
                    // 发送短信
                    $userInfo = (new User())->getUserinfo(['id' => $questionInfo['uid']]);
                    if ($userInfo && $userInfo['tel'])
                    {
                        Util::sendHySms([$userInfo['tel']], '', $smsTpid, $tpContent);
                    }
                } else
                {
                    Log::write('问答接单检测 如果未接单则退款 QuestionAnswerJob->AstrReceivingCheck  问答问题【' . $jobData['qid'] . '】退款失败:' . $res['msg'], 'error', true);
                }
            }
        }
        catch (\Exception $e)
        {
            $function = __FUNCTION__;
            Log::write("问答队列 异常QuestionAnswerJob->{$function}(),JobData = " . json_encode($jobData, JSON_UNESCAPED_UNICODE) . "：错误消息：{$e->getMessage()};FILE:{$e->getFile()};Line:{$e->getLine()}", 'error');
        }
        // 已被接单 ｜ 已取消
        $job->delete();
    }

    /**
     * 占星师 40分钟内还未回复的用户进行通知 检测
     * @param Job $job
     * @param $jobData
     * @throws \Exception
     */
    public function AstrReplyNotify(Job $job, $jobData)
    {
        // $jobData = [
        //     'task_id' =>任务ID
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }

        try
        {
            $astrTaskModel = new Zlcr2AstrTasks();
            $taskInfo = $astrTaskModel->getInfoById($jobData['task_id']);
            if ($taskInfo['status'] === 1)
            {   // 进行中
                $questionModel = new Zlcr2UserQuestion();
                $questionInfo = $questionModel->getInfoById($taskInfo['qid'], ['status', 'astr_id', 'uid']);
                if ($questionInfo['status'] === 4)
                {   // 如果40分钟了 占星师还未回复 发送 提醒消息
                    // 发送短信
                    $tel = (new ZlcrAstr())->getInfoById($questionInfo['astr_id'], ['tel']);
                    Util::sendHySms([$tel['tel']], '', 52338, ['others' => $taskInfo['qid'], 'time' => 10]);
                }
            }
        }
        catch (\Exception $e)
        {
            $function = __FUNCTION__;
            Log::write("问答队列 异常QuestionAnswerJob->{$function}(),JobData = " . json_encode($jobData, JSON_UNESCAPED_UNICODE) . "：错误消息：{$e->getMessage()};FILE:{$e->getFile()};Line:{$e->getLine()}", 'error');
        }

        $job->delete();
    }

    /**
     * 占星师 60分钟内还未回复的用户进行取消问题 检测
     * @param Job $job
     * @param $jobData
     * @throws \Exception
     */
    public function QuestionAstrReplyCheck(Job $job, $jobData)
    {
        // $jobData = [
        //     'task_id' =>任务ID
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }
        try
        {
            $nowTime = time();
            $astrTaskModel = new Zlcr2AstrTasks();
            $astrModel = new ZlcrAstr();
            $taskInfo = $astrTaskModel->getInfoById($jobData['task_id']);
            if ($taskInfo['status'] === 1)
            {   // 进行中
                $questionModel = new Zlcr2UserQuestion();
                $questionInfo = $questionModel->getInfoById($taskInfo['qid'], ['status', 'astr_id', 'uid', 'discard_num', 'question_type', 'order_num']);
                if ($questionInfo['status'] === 4)
                {   // 如果60分钟了 占星师还未回复 取消任务
                    // 弃答
                    if ($questionInfo['discard_num'] >= 2)
                    {
                        // 取消订单退款
                        $OrderModel = new \app\common\cachemodel\Orders();
                        $orders = $OrderModel->getInfoById($questionInfo['order_num']);
                        $res = $OrderModel->refund($questionInfo['uid'], $orders, $orders['total_amount']);
                        if ($res['status'])
                        {
                            // 问题弃答
                            $questionModel->UpdateData($taskInfo['qid'], [
                                'status' => 9,  // 弃答三次退款
                                'astr_id' => 0,
                                'astr_receiving_time' => 0,
                                'discard_num' => $questionInfo['discard_num'] + 1,
                            ]);
                            $msgContent = "你开启的悬赏问答，订单编号：{$questionInfo['order_num']}因问题无法回答自动取消，资金将原路返还，请注意查收。请检查问题重新下单。 ";
                            // 消息中心添加信息
                            $messageData = [
                                'status' => 0,
                                'is_read' => 0,
                                'range' => $questionInfo['uid'],
                                'type' => 2,
                                'reid' => 0,
                                'cid' => 4,//
                                'title' => '订单取消通知',
                                'content' => $msgContent,// 消息中心跳转地址
                                'link' => "order_details?order_id={$questionInfo['order_num']}&order_type=22&need_auth=0",  // 订单详情
                                'target' => 'local',
                                'create_time' => $nowTime
                            ];
                            (new MessageCenter())->pushMessage($questionInfo['uid'], $messageData);
                            $pushData = ['action' => 'extend', 'target' => 'local', 'link' => "order_details?order_id={$questionInfo['order_num']}&order_type=22&need_auth=0"];
                            // PUSH推送报告首页
                            (new Push())->pushUserMsg($questionInfo['uid'], $msgContent, $pushData);
                            // 发送短信
                            $userInfo = (new User())->getUserinfo(['id' => $questionInfo['uid']]);
                            if ($userInfo && $userInfo['tel'])
                            {
                                Util::sendHySms([$userInfo['tel']], '', 52340, ['order_num' => $questionInfo['order_num']]);
                            }
                        } else
                        {
                            Log::write('问答接单检测 如果未接单则退款 QuestionAnswerJob->QuestionAstrReplyCheck  问答问题【' . $taskInfo['qid'] . '】退款失败:' . $res['msg'], 'error', true);
                            // 问题弃答 退款失败 特殊处理
                            $questionModel->UpdateData($taskInfo['qid'], [
                                'astr_id' => 0,
                                'astr_receiving_time' => 0,
                                'discard_num' => $questionInfo['discard_num'] + 1,
                            ]);
                        }
                    } else
                    {
                        // 问题弃答
                        $questionModel->UpdateData($taskInfo['qid'], [
                            'astr_id' => 0,
                            'astr_receiving_time' => 0,
                            'discard_num' => $questionInfo['discard_num'] + 1,
                        ]);
                    }
                    // 获取近30天内 已经回复超时 次数
                    $monthBeforTime = strtotime("-1 month");
                    $timeOutNum = $astrTaskModel->where(['astr_id' => $questionInfo['astr_id'], 'question_type' => $questionInfo['question_type'], 'status' => 5, 'create_time' => ['>', $monthBeforTime]])->count();
                    // 更新占星师任务状态信息
                    $taskUpdate = [
                        'status' => 5,
                        'update_time' => $nowTime,
                    ];
                    // 扣分 或 扣分 并 冻结接单资格
                    // 任务回复超时 扣分
                    $isPause = false;
                    $astrModel->changeAstrScore($questionInfo['astr_id'], $taskInfo['qid'], -5, $questionInfo['question_type'], 8, 0);
                    if ($timeOutNum >= 2)
                    {   // 超时次数 已经有2次或以上了
                        $isPause = true;
                        $taskUpdate['is_lock_receiving'] = 1;
                        $astrModel->changeAstrScore($questionInfo['astr_id'], $taskInfo['qid'], -50, $questionInfo['question_type'], 10, 0);
                    } elseif ($timeOutNum === 1)
                    {   // 已经超时两次
                        $astrModel->changeAstrScore($questionInfo['astr_id'], $taskInfo['qid'], -10, $questionInfo['question_type'], 9, 0);
                    }
                    // 更新占星师任务状态信息
                    $astrTaskModel->UpdateData($jobData['task_id'], $questionInfo['astr_id'], $taskUpdate);
                    // 发送 占星师站内信
                    if ($questionInfo['question_type'] === 2)
                    {   // 骰子
                        $msgContent = $isPause ? "你的任务{$taskInfo['qid']}因回复超时被取消，因30天内3次回复超时，账号问答-骰子接单功能被封禁。"
                            : "你的任务{$taskInfo['qid']}因回复超时被取消，30天内3次回复超时账号将封禁接单功能。";
                    } else
                    {   // 塔罗 ｜ 星盘
                        $questionName = $questionInfo['question_type'] === 1 ? '占星' : '塔罗';
                        $msgContent = $isPause ? "你的任务{$taskInfo['qid']}因回复超时被取消，已扣除相应的能力分，因30天内3次回复超时，账号问答-{$questionName}接单功能被封禁。"
                            : "你的任务{$taskInfo['qid']}因回复超时被取消，已扣除相应的能力分，将会影响你的等级和收益，30天内3次回复超时账号将封禁接单功能。";
                    }

                    // 占星师站内信
                    (new ZlcrAstrMessage())->add($questionInfo['astr_id'], [
                        'status' => 0,
                        'is_read' => 0,
                        'astr_id' => $questionInfo['astr_id'],
                        'type' => 9, // 默认消息
                        'title' => '任务取消通知',
                        'content' => $msgContent,
                        'target' => 'local',
                        'link' => '/quiz/answer?task_id=' . $jobData['task_id'],
                        'create_time' => $nowTime
                    ]);
                }
            }
        }
        catch (\Exception $e)
        {
            $function = __FUNCTION__;
            Log::write("问答队列 异常QuestionAnswerJob->{$function}(),JobData = " . json_encode($jobData, JSON_UNESCAPED_UNICODE) . "：错误消息：{$e->getMessage()};FILE:{$e->getFile()};Line:{$e->getLine()}", 'error');
        }
        $job->delete();
    }

    /**
     * 任务完成 检测 占星师 回答48小时后
     * @param Job $job
     * @param $jobData
     * @throws \Exception
     */
    public function QuestionSuccess(Job $job, $jobData)
    {
        // $jobData = [
        //     'task_id' =>任务ID
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }
        try
        {
            $nowTime = time();
            $astrTaskModel = new Zlcr2AstrTasks();
            $astrModel = new ZlcrAstr();
            $orderModel = new Orders();
            $taskInfo = $astrTaskModel->getInfoById($jobData['task_id']);
            $questionModel = new Zlcr2UserQuestion();
            $questionInfo = $questionModel->getInfoById($taskInfo['qid'], ['status', 'astr_id', 'uid', 'discard_num', 'question_type', 'order_num', 'lock_reason', 'complain_status', 'gid', 'activity_discount', 'id', 'is_comment', 'return_answer_num', 'supplement_answer', 'reply_time']);
            if ($questionInfo['status'] === 5)
            {   // 已解答 待追问状态 仅 该状态进行完成操作 其他状态不处理 如在追问中，则追问回答的时候进行完成逻辑处理｜追问被取消时处理
                $isZhunleReply = false; // 官方是否介入 追问回复
                $addQuestionLists = (new Zlcr2UserAddQuestion())->getQuestionAddQuestionInfo($questionInfo['id']);
                if ($questionInfo['return_answer_num'] > 0)
                {   // 如果 补充回答过  判断是否到了结算时间
                    $lastStartTime = $questionInfo['reply_time']; // 任务结算开始时间 默认首次占星师回复时间       如果有退回重答的情况 则以最后的一个退回重答回复时间为准
                    foreach ($questionInfo['supplement_answer'] as $supplementAnswerItem)
                    {
                        if ($supplementAnswerItem['type'] === 2)
                        {   // 退回重答
                            $lastStartTime = $supplementAnswerItem['create_time'] > $lastStartTime ? $supplementAnswerItem['create_time'] : $lastStartTime;
                        }
                    }
                    foreach ($addQuestionLists as $addQuestionDatum)
                    {
                        if ($addQuestionDatum['status'] === 4 && $addQuestionDatum['supplement_answer'])
                        {
                            foreach ($addQuestionDatum['supplement_answer'] as $addQuestionSupplementAnswerItem)
                            {
                                $lastStartTime = $addQuestionSupplementAnswerItem['create_time'] > $lastStartTime ? $addQuestionSupplementAnswerItem['create_time'] : $lastStartTime;
                            }
                        }
                    }
                    $endTime = $lastStartTime + 172800 - $nowTime;
                    // 判断 是否到了结算时间
                    if ($endTime > 0)
                    { // 如果 还没有到结算时间
                        $job->release($endTime + 60); // 延迟到结算后一分钟 再次执行
                        return;
                    }
                }
                // 问答状态更新完成
                $questionModel->UpdateData($taskInfo['qid'], [
                    'status' => $questionInfo['lock_reason'] ? 7 : 6, // complain_status=》答案申述状态 0=>未申述 1=>已申述【待审核】2=>申述成功 3=>申述失败
                    'success_time' => $nowTime
                ]);
                // 订单状态 更新已完成
                // 问题 完成
                $orderDataUpdateState = $orderModel->UpdateData($questionInfo['order_num'], ['status' => 4], 4);
                if ($orderDataUpdateState === false)
                {
                    Log::write('任务完成更新问答订单状态失败 任务ID:' . $jobData['task_id'], 'error', true);
                }
                // 追问 完成
                foreach ($addQuestionLists as $addQuestionItem)
                {
                    if ($addQuestionItem['order_num'] && $addQuestionItem['status'] === 4)
                    {
                        $addUpdateOrder = $orderModel->UpdateData($addQuestionItem['order_num'], ['status' => 4], 4);
                        if ($addUpdateOrder === false)
                        {
                            Log::write('任务完成更新追问订单状态失败 任务ID:' . $jobData['task_id'], 'error', true);
                        }
                    }
                    if ($addQuestionItem['reply_type'] === 2)
                    {   // 官方介入 评论 不影响能力值
                        $isZhunleReply = true;
                    }
                }

                if ($taskInfo['status'] === 1)
                {   // 占星师任务状态正常
                    // 计算本单收益
                    $taskEarning = $questionModel->getQuestionEarning($questionInfo, $taskInfo);
                    // 占星师任务完成
                    $astrTaskModel->UpdateData($jobData['task_id'], $taskInfo['astr_id'], [
                        'status' => 2,
                        'earning' => $taskEarning['earning'],
                        'update_time' => $nowTime
                    ]);

                    if (empty($questionInfo['lock_reason']))
                    {
                        $astrInfo = $astrModel->getInfoById($taskInfo['astr_id']);
                        $teamId = $astrInfo['team_id'] ?? 0;
                        // 计算占星师收益 并 更新占星师收益 lock_reason冻结不更新收益
                        (new ZlcrAstrAccount())->astrQuestionAnswerEarningsSend([
                            'earning' => $taskEarning['earning'],
                            'total_amount' => $taskEarning['total_amount'],
                            'astr_id' => $taskInfo['astr_id'],
                            'type' => 1,
                            'gid' => $questionInfo['gid'],
                            'proportion' => $astrModel->getAstrQuestionAnswerProportion($taskInfo['create_time'], $questionInfo['question_type'], $taskInfo['qa_level']),
                            'question_type' => $questionInfo['question_type'],
                            'qid' => $taskInfo['qid'],
                            'team_id' => $teamId,
                        ]);
                    }
                }
                if ($questionInfo['is_comment'])
                {   // 用户已经评价过了
                    if (!$isZhunleReply)
                    {
                        $commentInfo = (new Zlcr2UserQuestionComment())->getInfoById($questionInfo['id']);
                        //评论等级和标签等级不符，不可评论
                        $astrModel->changeAstrScore($taskInfo['astr_id'], $taskInfo['qid'], $commentInfo['score'], $questionInfo['question_type'], 1, 0);
                    }
                } else
                {
                    // 如果没有评价 则发送 72小时候自动评价 队列
                    Util::queuePush('question_answer_question_comment_check', ['qid' => $taskInfo['qid']], 259200);
                }
            }
        }
        catch (\Exception $e)
        {
            $function = __FUNCTION__;
            Log::write("问答队列 异常QuestionAnswerJob->{$function}(),JobData = " . json_encode($jobData, JSON_UNESCAPED_UNICODE) . "：错误消息：{$e->getMessage()};FILE:{$e->getFile()};Line:{$e->getLine()}", 'error');
        }
        $job->delete();
    }

    /**
     * 问答 问题 评价检测 未评价 自动评价
     * @param Job $job
     * @param $jobData
     * @throws \Exception
     */
    public function QuestionCommentCheck(Job $job, $jobData)
    {
        // $jobData = [
        //     'qid' =>问题ID
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }
        try
        {
            $questionModel = new Zlcr2UserQuestion();
            $questionInfo = $questionModel->getInfoById($jobData['qid'], ['is_comment', 'astr_id']);

            if (!$questionInfo['is_comment'])
            {   // 没有评价 自动评价
                // 写入评价数据
                (new Zlcr2UserQuestionComment())->save([
                    'qid' => $jobData['qid'],
                    'level' => 3,
                    'tid' => 87,
                    'comment' => '',
                    'astr_id' => $questionInfo['astr_id'],
                    'comment_type' => 2,
                    'create_time' => time()
                ]);
                // 更新评价状态
                $questionModel->UpdateData($jobData['qid'], [
                    'is_comment' => 1
                ]);
            }
        }
        catch (\Exception $e)
        {
            $function = __FUNCTION__;
            Log::write("问答队列 异常QuestionAnswerJob->{$function}(),JobData = " . json_encode($jobData, JSON_UNESCAPED_UNICODE) . "：错误消息：{$e->getMessage()};FILE:{$e->getFile()};Line:{$e->getLine()}", 'error');
        }
        $job->delete();
    }

    /**
     * 追问回复超时检测
     * @param Job $job
     * @param $jobData
     * @throws \Exception
     */
    public function AddQuestionReplyTimeoutCheck(Job $job, $jobData)
    {
        // $jobData = [
        //     'add_question_id' =>追问ID
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }

        // 追问回复超时 付费  48小时内    免费 不检测
        /**
         * 1、48小时内
         * 用户 追问退款
         * 任务进行中，但不能追问了
         * 占星师 任务失败 结算
         * 2、超48小时
         * 用户退款
         * 任务自动完成
         * 占星师 任务失败 结算
         */
        try
        {
            $addQuestionModel = new Zlcr2UserAddQuestion();
            $addQuestionInfo = $addQuestionModel->getInfoById($jobData['add_question_id']);
            $nowTime = time();
            $astrTaskModel = new Zlcr2AstrTasks();
            $astrModel = new ZlcrAstr();

            if ($addQuestionInfo['status'] === 2)
            {
                $questionModel = new Zlcr2UserQuestion();
                $questionInfo = $questionModel->getInfoById($addQuestionInfo['qid'], ['status', 'astr_id', 'uid', 'question_type', 'order_num', 'is_comment', 'gid', 'activity_discount', 'id', 'reply_time']);
                if (empty($addQuestionInfo['order_num']))
                {   // 免费 想占星师 发送超时提醒
                    $taskInfo = $astrTaskModel->where(['astr_id' => $questionInfo['astr_id'], 'qid' => $addQuestionInfo['qid']])->find();
                    // 占星师站内信
                    (new ZlcrAstrMessage())->add($questionInfo['astr_id'], [
                        'status' => 0,
                        'is_read' => 0,
                        'astr_id' => $questionInfo['astr_id'],
                        'type' => 9, // 默认消息
                        'title' => '任务异常通知',
                        'content' => "你的任务{$taskInfo['qid']}追问回复已经超时，请尽快回复，官方介入后将扣除本任务收益。",
                        'target' => 'local',
                        'link' => '/quiz/answer?task_id=' . $taskInfo['id'],
                        'create_time' => $nowTime
                    ]);

                    // 发送短信 提醒  【准了】你的任务{task_id}有新的追问未回复，请尽快回复追问，回复超时将冻结任务收益
                    $tel = (new ZlcrAstr())->getInfoById($questionInfo['astr_id'], ['tel']);
                    Util::sendHySms([$tel['tel']], '', 53582, ['task_id' => $addQuestionInfo['qid']]);
                } else
                {
                    // 付费 并且还是待解答状态
                    // 追问退款
                    $OrderModel = new \app\common\cachemodel\Orders();
                    $orders = $OrderModel->getInfoById($addQuestionInfo['order_num']);
                    $res = $OrderModel->refund($questionInfo['uid'], $orders, $orders['total_amount']);
                    if ($res['status'])
                    {   // 追问状态关闭
                        $addQuestionModel->UpdateData($addQuestionInfo['qid'], $jobData['add_question_id'], [
                            'status' => 6,  // 状态 1=>待支付  2=>待解答 3=>未支付已关闭 4=>已完成 5=>占星师申述已取消  6=>追问回复超时已取消  7=>用户申述通过退款
                        ]);
                        // 问题更新至 已回答 不能追问
                        $questionModel->UpdateData($addQuestionInfo['qid'], ['status' => 5, 'lock_reason' => '咨询师追问回复超时']);
                        // 发送消息
                        // 消息中心添加信息
                        $messageData = [
                            'status' => 0,
                            'is_read' => 0,
                            'range' => $questionInfo['uid'],
                            'type' => 2,
                            'reid' => 0,
                            'cid' => 4,//
                            'title' => '问答追问取消通知',
                            'content' => '你开启的悬赏问答追问，订单编号：' . $addQuestionInfo['order_num'] . '因占星师超时未回复取消，资金将原路返还，请注意查收。',// 消息中心跳转地址
                            'link' => "question_detail?qid={$addQuestionInfo['qid']}&need_auth=0",
                            'target' => 'local',
                            'create_time' => $nowTime
                        ];
                        (new MessageCenter())->pushMessage($questionInfo['uid'], $messageData);
                        $pushData = ['action' => 'extend', 'target' => 'local', 'link' => "question_detail?qid={$addQuestionInfo['qid']}&need_auth=0"];
                        // PUSH推送报告首页
                        (new Push())->pushUserMsg($questionInfo['uid'], '你开启的悬赏问答追问，订单编号：' . $addQuestionInfo['order_num'] . '因占星师超时未回复取消，资金将原路返还，请注意查收。', $pushData);
                        // 占星师结算
                        $taskInfo = $astrTaskModel->where(['astr_id' => $questionInfo['astr_id'], 'qid' => $addQuestionInfo['qid']])->find();
                        // 计算本单收益
                        $taskEarning = $questionModel->getQuestionEarning($questionInfo, ['qa_level' => $taskInfo['qa_level'], 'create_time' => (int)$taskInfo['create_time']]);
                        // 获取近30天内 已经回复超时 次数
                        $monthBeforTime = strtotime("-1 month");
                        $timeOutNum = $astrTaskModel->where(['astr_id' => $questionInfo['astr_id'], 'question_type' => $questionInfo['question_type'], 'status' => 6, 'create_time' => ['>', $monthBeforTime]])->count();
                        // 任务关闭数据
                        $taskUpdate = [
                            'status' => 6,
                            'update_time' => $nowTime,
                            'deduct_earning_time' => $nowTime,
                            'earning' => $taskEarning['earning'],
                        ];
                        // 扣除能力分
                        //评论等级和标签等级不符，不可评论
                        $astrModel->changeAstrScore($taskInfo['astr_id'], $taskInfo['qid'], -2, $questionInfo['question_type'], 11, 0);
                        // 获取超时次数 或扣除额外能力分 或冻结账号
                        $isPause = false;
                        if ($timeOutNum >= 2)
                        {
                            $isPause = true;
                            $taskUpdate['is_lock_receiving'] = 1;
                            $astrModel->changeAstrScore($questionInfo['astr_id'], $taskInfo['qid'], -10, $questionInfo['question_type'], 13, 0);
                        } elseif ($timeOutNum === 1)
                        {
                            $astrModel->changeAstrScore($questionInfo['astr_id'], $taskInfo['qid'], -5, $questionInfo['question_type'], 12, 0);
                        }
                        // 任务状态关闭
                        $astrTaskModel->UpdateData((int)$taskInfo['id'], $questionInfo['astr_id'], $taskUpdate);
                        // 发送 占星师站内信
                        if ($questionInfo['question_type'] === 2)
                        {   // 骰子
                            $msgContent = $isPause ? "你的任务{$taskInfo['qid']}追问回复超时，因30日内3次追问回复超时，问答-骰子接单资格冻结，已经扣除你本任务的全部收益。如有疑问请联系官方。"
                                : "因你的任务{$taskInfo['qid']}追问回复超时，已经扣除你本任务的全部收益。";
                        } else
                        {   // 塔罗 ｜ 星盘
                            $questionName = $questionInfo['question_type'] === 1 ? '占星' : '塔罗';
                            $msgContent = $isPause ? "你的任务{$taskInfo['qid']}追问回复超时，因30日内3次追问回复超时，问答-{$questionName}接单资格冻结，已经扣除你本任务的全部收益。如有疑问请联系官方。"
                                : "因你的任务{$taskInfo['qid']}追问回复超时，已经扣除你本任务的全部收益，并做扣除能力分处理。如有疑问请联系官方。";
                        }

                        // 占星师站内信
                        (new ZlcrAstrMessage())->add($questionInfo['astr_id'], [
                            'status' => 0,
                            'is_read' => 0,
                            'astr_id' => $questionInfo['astr_id'],
                            'type' => 9, // 默认消息
                            'title' => '任务异常通知',
                            'content' => $msgContent,
                            'target' => 'local',
                            'link' => '/quiz/answer?task_id=' . $taskInfo['id'],
                            'create_time' => $nowTime
                        ]);

                        // 如果咨询时间 距离现在超过48小时了 则结算任务 添加结算队列 延迟5秒
                        if ($nowTime > $questionInfo['reply_time'] + 172800)
                        {   // 任务完成
                            Util::queuePush('question_answer_question_success_check', ['task_id' => $taskInfo['id']], 5);
                        }
                    }
                }
            }
        }
        catch (\Exception $e)
        {
            $function = __FUNCTION__;
            Log::write("问答队列 异常QuestionAnswerJob->{$function}(),JobData = " . json_encode($jobData, JSON_UNESCAPED_UNICODE) . "：错误消息：{$e->getMessage()};FILE:{$e->getFile()};Line:{$e->getLine()}", 'error');
        }
        $job->delete();
    }

    /**
     * 白天 追问回复检测 未回复发送消息提醒
     * @param Job $job
     * @param $jobData
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function AddQuestionReplyNotifyCheck(Job $job, $jobData)
    {
        // $jobData = [
        //     'add_question_id' =>追问ID
        //     'astr_id' =>占星师ID
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }
        try
        {
            $addQuestionModel = new Zlcr2UserAddQuestion();
            $addQuestionInfo = $addQuestionModel->getInfoById($jobData['add_question_id']);

            if ($addQuestionInfo['status'] === 2)   //状态 1=>待支付  2=>待解答 3=>未支付已关闭 4=>已完成 5=>占星师申述已取消  6=>追问回复超时已取消  7=>用户申述通过退款
            {   // 发送短信 提醒  【准了】你的任务{task_id}有新的追问未回复，请尽快回复追问，回复超时将冻结任务收益
                $tel = (new ZlcrAstr())->getInfoById($jobData['astr_id'], ['tel']);
                Util::sendHySms([$tel['tel']], '', 62664, ['task_id' => $addQuestionInfo['qid']]);
            }
        }
        catch (\Exception $e)
        {
            $function = __FUNCTION__;
            Log::write("问答队列 异常QuestionAnswerJob->{$function}(),JobData = " . json_encode($jobData, JSON_UNESCAPED_UNICODE) . "：错误消息：{$e->getMessage()};FILE:{$e->getFile()};Line:{$e->getLine()}", 'error');
        }
        $job->delete();
    }

    /**
     * 占星师 回复40小时后 用户还未追问过
     * @param Job $job
     * @param $jobData
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function AddQuestionNotify(Job $job, $jobData)
    {
        // $jobData = [
        //     'qid' => 问题ID
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }
        try
        {
            $nowTime = time();
            $questionModel = new Zlcr2UserQuestion();
            $questionInfo = $questionModel->getInfoById($jobData['qid'], ['status', 'astr_id', 'order_num', 'uid', 'lock_reason', 'supplement_answer']);
            if ($questionInfo['status'] === 5 && empty($questionInfo['lock_reason']) && !(new Zlcr2UserAddQuestion())->getQuestionIsAddQuestion($jobData['qid']))
            {   // 判断是否有过 重答的情况
                foreach ($questionInfo['supplement_answer'] as $itemData)
                {
                    if ($itemData['type'] == 2)
                    {   // 有补充回答
                        if ($nowTime - $itemData['create_time'] >= 143400)
                        {   // 剩余 时间 小于 8小时10分钟
                            $job->delete();
                            return;
                        }
                    }
                }
                // 等待追问中   问题没有冻结
                $msgContent = "你的问答订单{$questionInfo['order_num']}追问入口还有8小时关闭，如果你还有疑问询问咨询师，请尽快完成追问。";
                // 消息中心添加信息
                $messageData = [
                    'status' => 0,
                    'is_read' => 0,
                    'range' => $questionInfo['uid'],
                    'type' => 2,
                    'reid' => 0,
                    'cid' => 4,//
                    'title' => '追问提醒',
                    'content' => $msgContent,// 消息中心跳转地址
                    'link' => "question_detail?qid={$jobData['qid']}&comment_id=0&is_answer_detail=0&need_auth=0",  // 订单详情
                    'target' => 'local',
                    'create_time' => $nowTime
                ];
                (new MessageCenter())->pushMessage($questionInfo['uid'], $messageData);
                $pushData = ['action' => 'extend', 'target' => 'local', 'link' => "question_detail?qid={$jobData['qid']}&comment_id=0&is_answer_detail=0&need_auth=0"];
                // PUSH推送报告首页
                (new Push())->pushUserMsg($questionInfo['uid'], $msgContent, $pushData);
                // 发送短信
                $userInfo = (new User())->getUserinfo(['id' => $questionInfo['uid']]);
                if ($userInfo && $userInfo['tel'])
                {
                    Util::sendHySms([$userInfo['tel']], '', 52348, ['order_num' => $jobData['qid']]);
                }
            }
        }
        catch (\Exception $e)
        {
            $function = __FUNCTION__;
            Log::write("问答队列 异常QuestionAnswerJob->{$function}(),JobData = " . json_encode($jobData, JSON_UNESCAPED_UNICODE) . "：错误消息：{$e->getMessage()};FILE:{$e->getFile()};Line:{$e->getLine()}", 'error');
        }
        $job->delete();
    }

    /**
     * 占星师 补充回答检测
     */
    public function QuestionSupplementAnswerCheck(Job $job, $jobData)
    {
        // $jobData = [
        //     'appeal_id' =>申诉ID,
        //     'task_id' => 占星师任务ID
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }
        $taskId = $jobData['task_id'];
        $astrTaskModel = new Zlcr2AstrTasks();
        $zlcrAppealModel = new ZlcrAppeal();
        $questionModel = new Zlcr2UserQuestion();
        $orderModel = new Orders();
        $addQuestionModel = new Zlcr2UserAddQuestion();
        $nowTime = time();

        $appealInfo = $zlcrAppealModel->where(['id' => $jobData['appeal_id']])->order('id desc')->find();
        if ($appealInfo['return_answer_status'] != 0)
        {
            $job->delete();
            return;
        }
        // 获取问题信息
        $questionInfo = $questionModel->getInfoById($appealInfo['qid']);
        // 获取占星师任务ID
        $taskInfo = $astrTaskModel->getInfoById($taskId);

        try
        {
            $zlcrAppealModel->updateData($appealInfo['id'], $taskInfo['astr_id'], $taskInfo['qid'], 3, ['return_answer_status' => 3]);
            //问题状态处理
            $questionModel->UpdateData($taskInfo['qid'], ['lock_reason' => '主动放弃退回重答', 'complain_status' => 5, 'status' => 21, 'update_time' => $nowTime, 'success_time' => $nowTime]);
            //问题订单状态处理
            $orderModel->UpdateData($questionInfo['order_num'], ['status' => 4, 'update_time' => $nowTime], 4);
            $addQuestionLists = $addQuestionModel->getQuestionAddQuestionInfo($questionInfo['id']);
            foreach ($addQuestionLists as $addQuestionItem)
            {
                if ($addQuestionItem['status'] === 4 && $addQuestionItem['order_num'])
                {
                    $orderModel->UpdateData($addQuestionItem['order_num'], ['status' => 4], 4);
                }
            }
            $msgContent = "非常抱歉，由于咨询师的回答未通过人工审核，你的问答订单：{$questionInfo['order_num']}现已判定申诉成立，资金将在7个工作日内原路返还，请注意查收。";
            // 计算本单收益
            $taskEarning = $questionModel->getQuestionEarning($questionInfo, $taskInfo);
            //更新占星师任务状态
            $astrTaskModel->UpdateData($taskId, $taskInfo['astr_id'], ['status' => 7, 'lock_earning' => 1, 'deduct_earning_time' => $nowTime, 'update_time' => $nowTime, 'earning' => $taskEarning['earning']]);
            //审核通过，添加消息中心
            $msg = [
                'range' => $questionInfo['uid'],
                'type' => 1,
                'cid' => 1,
                'is_read' => 0,
                'title' => '订单取消通知',
                'content' => $msgContent,
                'link' => "question_detail?qid={$questionInfo['id']}&comment_id=0&is_answer_detail=0&need_auth=0",
                'target' => "local",
                'create_time' => $nowTime
            ];
            (new MessageCenter())->pushMessage($questionInfo['uid'], $msg);
            // 占星师站内信
            (new ZlcrAstrMessage())->add($questionInfo['astr_id'], [
                'status' => 0,
                'is_read' => 0,
                'astr_id' => $questionInfo['astr_id'],
                'type' => 9, // 默认消息
                'title' => '任务取消通知',
                'content' => "由于您放弃/未及时对任务进行重答，任务{$questionInfo['id']}的收益将被冻结，如有疑问请联系官方。",
                'target' => 'local',
                'link' => '/quiz/answer?task_id=' . $taskId,
                'create_time' => $nowTime
            ]);
            $userInfo = (new User())->getUserinfo(['id' => $questionInfo['uid']]);
            if ($userInfo['tel'])
            {
                Util::sendHySms([$userInfo['tel']], '', 91373, ['order_id' => $questionInfo['id']]);//申诉成立给用户发短信
            }
        }
        catch (\Exception $e)
        {
            Log::write("占星师 补充回答超时 错误消息：{$e->getMessage()};FILE:{$e->getFile()};Line:{$e->getLine()}", 'error');
        }

        $job->delete();
    }
}
